package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Order;
import com.sky.exception.BaseException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);
        // 获取营业额列表
        List<BigDecimal> turnoverList = dateList.stream()
                .map(date -> {
                    Map<String, Object> map = getBeginAndEndTime(date);
                    map.put("status", Order.COMPLETED);
                    BigDecimal sumAccount = orderMapper.sumAccountByMap(map);
                    return sumAccount == null ? BigDecimal.ZERO : sumAccount;
                })
                .collect(Collectors.toList());
        // 封装VO并返回
        return new TurnoverReportVO(StringUtils.join(dateList, ","),
                StringUtils.join(turnoverList, ","));
    }


    /**
     * 用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);
        List<Long> newUserList = new ArrayList<>();
        List<Long> totalUserList = new ArrayList<>();
        // 获取用户数据列表
        dateList.forEach(date -> {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            // 查询新增用户数
            Long sumNewUser = orderMapper.sumNewUserByTime(beginTime, endTime);
            // 查询总用户数
            Long sumTotalUser = orderMapper.sumTotalUserByTime(endTime);
            newUserList.add(sumNewUser == null ? 0L : sumNewUser);
            totalUserList.add(sumTotalUser == null ? 0L : sumTotalUser);
        });
        return new UserReportVO(
                StringUtils.join(
                        dateList, ","),
                StringUtils.join(
                        totalUserList, ","),
                StringUtils.join(
                        newUserList, ",")
        );
    }

    /**
     * 订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);
        List<Long> orderCountList = new ArrayList<>();
        List<Long> validOrderCountList = new ArrayList<>();
        dateList.forEach(date -> {
            Map<String, Object> dayMap = getBeginAndEndTime(date);
            // 查询每日订单数
            Long orderCount = orderMapper.countOrder(dayMap);
            // 查询每日有效订单数
            dayMap.put("status", Order.COMPLETED);
            Long validOrder = orderMapper.countOrder(dayMap);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrder);
        });
        // 订单总数、有效订单数
        Map<String, Object> totalMap = new HashMap<>();
        Integer totalOrder = orderMapper.countOrder(totalMap).intValue();
        totalMap.put("status", Order.COMPLETED);
        Integer validOrder = orderMapper.countOrder(totalMap).intValue();
        return new OrderReportVO(
                StringUtils.join(dateList, ","),
                StringUtils.join(orderCountList, ","),
                StringUtils.join(validOrderCountList, ","),
                totalOrder,
                validOrder,
                validOrder.doubleValue() / totalOrder.doubleValue()// 订单完成率
        );
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        // 商品名称列表
        List<String> nameList = new ArrayList<>();
        // 销量列表
        List<String> numberList = new ArrayList<>();
        // 获取销量数据
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        // 查询当天有效订单销量前十
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getSalesTop10(beginTime, endTime, Order.COMPLETED);
        if (goodsSalesDTOList != null && !goodsSalesDTOList.isEmpty()) {
            goodsSalesDTOList.forEach(goodsSalesDTO -> {
                nameList.add(goodsSalesDTO.getName());
                numberList.add(goodsSalesDTO.getNumber().toString());
            });
        }
        return new SalesTop10ReportVO(
                StringUtils.join(nameList, ","),
                StringUtils.join(numberList, ",")
        );
    }


    private static List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        // 参数校验
        if (begin == null || end == null || begin.isAfter(end)) {
            throw new BaseException("时间异常");
        }
        // 获取时间列表
        List<LocalDate> timeList = new ArrayList<>();
        timeList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            timeList.add(begin);
        }
        return timeList;
    }

    public static Map<String,Object> getBeginAndEndTime(LocalDate date) {
        LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
        Map<String, Object> map = new HashMap<>();
        map.put("begin", beginTime);
        map.put("end", endTime);
        return map;
    }
}
